package org.pwwong.scalautils.signals

import scala.collection.Set
import org.pwwong.scalautils.event.Event

object EvalSignal{
  def apply[T](evaluator:()=>T, deps:Event[_]*) = new EvalSignal[T](evaluator,Set(deps:_*))
}

class EvalSignal[T](evaluator:()=>T, protected val onDependencies:Set[Event[_]]) extends Signal[T] {
  protected var value: T = reevaluate
  
  def apply():T = value
  
  def reevaluate:T = {
    val newValue:T = evaluator()   
    if(newValue != value){
      value=newValue
      onChange.fire(value)
    }
    return value
  }
  
  // Constructor
  for(onDep <- onDependencies){
    onDep(this){tmp => reevaluate}
  }
}
